package com.xixi.demo.service;

import com.xixi.demo.config.CaptchaProperties;
import com.xixi.demo.mapper.BlogMapper;
import com.xixi.demo.mapper.UserMapper;
import com.xixi.demo.model.BlogInfo;
import com.xixi.demo.model.Result;
import com.xixi.demo.model.UserInfo;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayDataSource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private CaptchaProperties captchaProperties;

    private final static long VALID_MILLIS_TIME = 60 * 1000;

    public UserInfo selectUserInfoByName(String userName) {
        return userMapper.selectByName(userName);
    }

    public UserInfo selectUserInfoById(Integer userId) {
        UserInfo userInfo =  userMapper.selectById(userId);
        userInfo.setContentCount(userMapper.selectCount(userId));
        return userInfo;
    }

    public UserInfo getAuthorInfo(Integer blogId) {
        BlogInfo blogInfo = blogMapper.selectById(blogId);
        if(blogInfo == null){
            return null;
        }
        UserInfo userInfo =  userMapper.selectById(blogInfo.getUserId());
        userInfo.setContentCount(userMapper.selectCount(blogInfo.getUserId()));
        return userInfo;

    }

    public Integer registry(String userName, String password, String githubUrl) {
        return userMapper.insertUser(userName, password, githubUrl);
    }
    public Result<Boolean> checkHomeCaptcha(String captcha, HttpSession session){
        String sessionCaptcha = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date sessionDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if(captcha.equalsIgnoreCase(sessionCaptcha)){
            if(System.currentTimeMillis() - sessionDate.getTime() < VALID_MILLIS_TIME){
                return Result.success(true);
            }else{
                return Result.overTimeCaptcha(false);
            }
        }
        return Result.errorCaptcha(false);
    }
}
